import Vue from 'vue'
import Vuex from 'vuex'
import {userLogin} from '../api/user'
Vue.use(Vuex)
import {getUserInfo,setUserInfo,getToken,setToken} from '../utils/auth.js'

export default new Vuex.Store({
  state: {
    // user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
    // token: localStorage.getItem('token') ? localStorage.getItem('token') : null
    user: getUserInfo() ? getUserInfo() : null,
    token: getToken() ? getToken() :null
  },
  mutations: {
    changeUser(state,payload){
      state.user = payload
      // localStorage.setItem('user',JSON.stringify(payload))
      setUserInfo(payload)
    },
    changeToken(state,data){
      state.token = data
      // localStorage.setItem('token',data)
      setToken(data)
    },
    tuichu(state){
      state.user = '',
      state.token = ''
    }
  },
  actions: {
    login({commit},data){
      return new Promise((resolve,reject)=>{
        userLogin(data.username,data.password).then(response=>{
          resolve(response)
          commit('changeUser',response.data.data)
          commit('changeToken',response.data.data.token)
        }).catch(error=>{
          reject(error)
        })
      })
    }
  },
  modules: {
  }
})
